package com.movies.service.controller.common;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;


@RestController
@RequestMapping("/file")
public class UploadController {

    @Value("${pictureFile.path}")
    private String picturePath;

    @Value("${pictureFile.path-mapping}")
    private String picturePathMapping;

//    上传单个文件
    @PostMapping("/upload")
    @SaCheckLogin
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error(Constants.CODE_600, "文件为空");
        }
        // 限制最大 5MB
        if (file.getSize() > 5L * 1024 * 1024) {
            return Result.error(Constants.CODE_600, "文件过大，最大 5MB");
        }
        String original = file.getOriginalFilename();
        String ext = "";
        if (original != null && original.contains(".")) {
            ext = original.substring(original.lastIndexOf('.') + 1).toLowerCase();
        }
        if (ext.isEmpty()) {
            ext = "png"; // 默认扩展名
        }
        java.util.Set<String> whitelist = new java.util.HashSet<>(java.util.Arrays.asList("jpg","jpeg","png","gif","webp"));
        if (!whitelist.contains(ext)) {
            return Result.error(Constants.CODE_600, "不支持的文件类型");
        }
        String random = UUID.randomUUID().toString().replace("-", "");
        String fileName = "upload." + random + "." + ext;
        try {
            java.nio.file.Path dir = java.nio.file.Paths.get(picturePath);
            java.nio.file.Files.createDirectories(dir);
            java.nio.file.Path target = dir.resolve(fileName);
            try (java.io.InputStream in = file.getInputStream()) {
                java.nio.file.Files.copy(in, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            }
            String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
            String mapping = picturePathMapping.endsWith("/") ? picturePathMapping : (picturePathMapping + "/");
            String fullUrl = baseUrl + mapping + fileName;
            return Result.success("上传成功", fullUrl);
        } catch (java.io.IOException e) {
            return Result.error(Constants.CODE_600, "保存失败: " + e.getMessage());
        }
    }

//    富文本图片上传
    @PostMapping("/rich-text-image")
    @SaCheckLogin
    public Result uploadRichTextImage(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error(Constants.CODE_600, "文件为空");
        }
        // 限制最大 5MB
        if (file.getSize() > 5L * 1024 * 1024) {
            return Result.error(Constants.CODE_600, "文件过大，最大 5MB");
        }
        String original = file.getOriginalFilename();
        String ext = "";
        if (original != null && original.contains(".")) {
            ext = original.substring(original.lastIndexOf('.') + 1).toLowerCase();
        }
        if (ext.isEmpty()) {
            ext = "png"; // 默认扩展名
        }
        java.util.Set<String> whitelist = new java.util.HashSet<>(java.util.Arrays.asList("jpg","jpeg","png","gif","webp"));
        if (!whitelist.contains(ext)) {
            return Result.error(Constants.CODE_600, "不支持的文件类型");
        }
        String random = java.util.UUID.randomUUID().toString().replace("-", "");
        String fileName = "rich." + random + "." + ext;
        try {
            java.nio.file.Path dir = java.nio.file.Paths.get(picturePath);
            java.nio.file.Files.createDirectories(dir);
            java.nio.file.Path target = dir.resolve(fileName);
            try (java.io.InputStream in = file.getInputStream()) {
                java.nio.file.Files.copy(in, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            }
            String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
            String mapping = picturePathMapping.endsWith("/") ? picturePathMapping : (picturePathMapping + "/");
            String fullUrl = baseUrl + mapping + fileName;
            return Result.success("上传成功", fullUrl);
        } catch (java.io.IOException e) {
            return Result.error(Constants.CODE_600, "保存失败: " + e.getMessage());
        }
    }
}